import React, { useState, useEffect } from 'react';
import { ClassData } from '../mock/classData';
import { classService } from '../services/ClassService';

// 定义表单数据类型
interface ClassFormData extends Omit<ClassData, 'id'> {}

/**
 * 班级管理组件
 * 提供班级信息的增删改查功能
 */
const ClassManagement: React.FC = () => {
  const [classes, setClasses] = useState<ClassData[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isEditMode, setIsEditMode] = useState(false);
  const [currentClass, setCurrentClass] = useState<ClassData | null>(null);
  const [formData, setFormData] = useState<ClassFormData>({
      className: '',
      major: 1,
      counselor: '',
      lecturer: '',
      description: ''
    });
  const [loading, setLoading] = useState(true);
  const [filterGrade, setFilterGrade] = useState<string>('');
  const [sortField, setSortField] = useState<keyof ClassData>('className');
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc');
  const [formErrors, setFormErrors] = useState<Record<string, string>>({});

  // 获取班级数据
  const fetchClasses = async () => {
    setLoading(true);
    try {
      const data = await classService.getClasses();
      setClasses(data);
    } catch (error) {
      console.error('获取班级数据失败:', error);
      alert('获取班级数据失败: ' + (error instanceof Error ? error.message : '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  // 添加班级
  const addClass = async (values: ClassFormData) => {
    try {
      const newClass = await classService.addClass(values);
      setClasses([...classes, newClass]);
      alert('添加班级成功');
      return true;
    } catch (error) {
      console.error('添加班级失败:', error);
      alert('添加班级失败: ' + (error instanceof Error ? error.message : '未知错误'));
      return false;
    }
  };

  // 更新班级
  const updateClass = async (values: ClassFormData) => {
    if (!currentClass) return false;
    try {
      const updatedClass = await classService.updateClass(currentClass.id, values);
      if (updatedClass) {
        setClasses(classes.map(cls => cls.id === currentClass.id ? updatedClass : cls));
        alert('更新班级成功');
        return true;
      }
      return false;
    } catch (error) {
      console.error('更新班级失败:', error);
      alert('更新班级失败: ' + (error instanceof Error ? error.message : '未知错误'));
      return false;
    }
  };

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  // 验证表单
  const validateForm = () => {
    const errors: Record<string, string> = {};

    if (!formData.className.trim()) {
      errors.className = '班级名称不能为空';
    }

    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  // 处理表单提交
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (validateForm()) {
      const success = isEditMode ? await updateClass(formData) : await addClass(formData);
      if (success) {
        setIsModalVisible(false);
      }
    }
  };

  // 处理表单取消
  const handleCancel = () => {
    setIsModalVisible(false);
    setFormErrors({});
  };

  // 处理排序
  const handleSort = (field: keyof ClassData) => {
    if (sortField === field) {
      setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc');
    } else {
      setSortField(field);
      setSortDirection('asc');
    }
  };

  // 过滤和排序数据
  const filteredAndSortedClasses = React.useMemo(() => {
    let result = [...classes];

    // 过滤
    if (filterGrade) {
      result = result.filter(cls => cls.className.includes(filterGrade));
    }

    // 排序
    result.sort((a, b) => {
      const aValue = a[sortField];
      const bValue = b[sortField];

      if (typeof aValue === 'number' && typeof bValue === 'number') {
        return sortDirection === 'asc' ? aValue - bValue : bValue - aValue;
      } else {
        const aStr = String(aValue);
        const bStr = String(bValue);
        return sortDirection === 'asc' ? aStr.localeCompare(bStr) : bStr.localeCompare(aStr);
      }
    });

    return result;
  }, [classes, filterGrade, sortField, sortDirection]);

  // 获取年级列表
  const gradeOptions = React.useMemo(() => {
    const grades = Array.from(new Set(classes.map(cls => cls.className.substring(0, 4))));
    return grades.sort();
  }, [classes]);

  // 显示添加模态框
  const showAddModal = () => {
    setIsEditMode(false);
    setCurrentClass(null);
    setFormData({
      className: '',
      major: 1,
      counselor: '',
      lecturer: '',
      description: ''
    });
    setFormErrors({});
    setIsModalVisible(true);
  };

  // 显示编辑模态框
  const showEditModal = (cls: ClassData) => {
    setIsEditMode(true);
    setCurrentClass(cls);
    setFormData({
      className: cls.className,
      major: cls.major,
      counselor: cls.counselor,
      lecturer: cls.lecturer,
      description: cls.description
    });
    setFormErrors({});
    setIsModalVisible(true);
  };

  // 删除班级
  const deleteClass = async (id: string) => {
    if (!window.confirm('确定要删除这个班级吗？')) return;
    try {
      const success = await classService.deleteClass(id);
      if (success) {
        setClasses(classes.filter(cls => cls.id !== id));
        alert('删除班级成功');
      }
    } catch (error) {
      console.error('删除班级失败:', error);
      alert('删除班级失败: ' + (error instanceof Error ? error.message : '未知错误'));
    }
  };

  // 组件挂载时获取数据
  useEffect(() => {
    // 清除可能的旧数据
    localStorage.removeItem('classes');
    localStorage.removeItem('classData');
    localStorage.removeItem('class_info');
    
    fetchClasses();
  }, []);

  // 获取专业名称
  const getMajorName = (majorId: number) => {
    return majorId === 1 ? '专业1' : '专业2';
  };

  // 样式定义 - 合并为单个对象
  const styles: Record<string, React.CSSProperties> = {
    container: {
      padding: '20px',
      fontFamily: '-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica Neue, Arial, sans-serif'
    },
    header: {
      display: 'flex',
      justifyContent: 'space-between',
      alignItems: 'center',
      marginBottom: '20px',
      paddingBottom: '10px',
      borderBottom: '1px solid #e8e8e8'
    },
    title: {
      fontSize: '20px',
      fontWeight: 500,
      color: '#333'
    },
    addButton: {
      padding: '8px 16px',
      backgroundColor: '#1890ff',
      color: 'white',
      border: 'none',
      borderRadius: '4px',
      cursor: 'pointer',
      fontSize: '14px',
      transition: 'background-color 0.3s'
    },
    filterContainer: {
      marginBottom: '20px',
      display: 'flex',
      alignItems: 'center'
    },
    filterLabel: {
      marginRight: '8px',
      fontSize: '14px',
      color: '#333'
    },
    filterSelect: {
      padding: '6px 12px',
      border: '1px solid #d9d9d9',
      borderRadius: '4px',
      fontSize: '14px'
    },
    tableContainer: {
      overflowX: 'auto',
      border: '1px solid #e8e8e8',
      borderRadius: '4px'
    },
    loading: {
      padding: '40px',
      textAlign: 'center',
      color: '#666'
    },
    table: {
      width: '100%',
      borderCollapse: 'collapse'
    },
    tableHeaderRow: {
      backgroundColor: '#fafafa'
    },
    tableHeader: {
      padding: '12px 16px',
      textAlign: 'left',
      fontWeight: 500,
      color: '#333',
      borderBottom: '1px solid #e8e8e8',
      cursor: 'pointer'
    },
    tableHeaderHover: {
      transition: 'background-color 0.3s'
    },
    tableRow: {
      padding: '12px 16px',
      borderBottom: '1px solid #e8e8e8',
      color: '#333'
    },
    tableCell: {
      padding: '12px 16px',
      borderBottom: '1px solid #e8e8e8',
      color: '#333'
    },
    editButton: {
      padding: '4px 12px',
      backgroundColor: '#1890ff',
      color: 'white',
      border: 'none',
      borderRadius: '4px',
      cursor: 'pointer',
      fontSize: '12px',
      marginRight: '8px',
      transition: 'background-color 0.3s'
    },
    deleteButton: {
      padding: '4px 12px',
      backgroundColor: '#ff4d4f',
      color: 'white',
      border: 'none',
      borderRadius: '4px',
      cursor: 'pointer',
      fontSize: '12px',
      transition: 'background-color 0.3s'
    },
    modalOverlay: {
      position: 'fixed',
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      backgroundColor: 'rgba(0, 0, 0, 0.45)',
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      zIndex: 1000
    },
    modalContent: {
      backgroundColor: 'white',
      padding: '24px',
      borderRadius: '4px',
      width: '90%',
      maxWidth: '520px',
      maxHeight: '80vh',
      overflowY: 'auto'
    },
    modalHeader: {
      fontSize: '18px',
      fontWeight: 500,
      marginBottom: '20px',
      color: '#333'
    },
    formGroup: {
      marginBottom: '16px'
    },
    formLabel: {
      display: 'block',
      marginBottom: '8px',
      fontSize: '14px',
      color: '#333',
      fontWeight: 500
    },
    formInput: {
      width: '100%',
      padding: '8px 12px',
      border: '1px solid #d9d9d9',
      borderRadius: '4px',
      fontSize: '14px',
      boxSizing: 'border-box'
    },
    formTextarea: {
      width: '100%',
      padding: '8px 12px',
      border: '1px solid #d9d9d9',
      borderRadius: '4px',
      fontSize: '14px',
      boxSizing: 'border-box'
    },
    formActions: {
      display: 'flex',
      justifyContent: 'flex-end',
      marginTop: '24px'
    },
    cancelButton: {
      padding: '8px 16px',
      marginRight: '8px',
      border: '1px solid #d9d9d9',
      backgroundColor: 'white',
      borderRadius: '4px',
      cursor: 'pointer',
      fontSize: '14px',
      transition: 'all 0.3s'
    },
    submitButton: {
      padding: '8px 16px',
      backgroundColor: '#1890ff',
      color: 'white',
      border: 'none',
      borderRadius: '4px',
      cursor: 'pointer',
      fontSize: '14px',
      transition: 'background-color 0.3s'
    },
    errorText: {
      color: '#ff4d4f',
      fontSize: '12px',
      marginTop: '4px'
    }
  };

  return (
    <div style={styles.container}>
      <div style={styles.header}>
        <h1 style={styles.title}>班级管理</h1>
        <button style={styles.addButton} onClick={showAddModal}>
          添加班级
        </button>
      </div>

      <div style={styles.filterContainer}>
        <label style={styles.filterLabel} htmlFor="gradeFilter">
          按年级筛选:
        </label>
        <select
          id="gradeFilter"
          style={styles.filterSelect}
          value={filterGrade}
          onChange={(e) => setFilterGrade(e.target.value)}
        >
          <option value="">全部年级</option>
          {gradeOptions.map(grade => (
            <option key={grade} value={grade}>{grade}</option>
          ))}
        </select>
      </div>

      <div style={styles.tableContainer}>
        {loading ? (
          <div style={styles.loading}>加载中...</div>
        ) : (
          <table style={styles.table}>
            <thead>
              <tr style={styles.tableHeaderRow}>
                <th style={styles.tableHeader} onClick={() => handleSort('className')}>
                  班级名称 {sortField === 'className' && (sortDirection === 'asc' ? '↑' : '↓')}
                </th>
                <th style={styles.tableHeader}>专业</th>
                <th style={styles.tableHeader}>导员</th>
                <th style={styles.tableHeader}>讲师</th>
                <th style={styles.tableHeader}>操作</th>
              </tr>
            </thead>
            <tbody>
              {filteredAndSortedClasses.map(cls => (
                <tr key={cls.id} style={styles.tableRow}>
                  <td style={styles.tableCell}>{cls.className}</td>
                  <td style={styles.tableCell}>{getMajorName(cls.major)}</td>
                  <td style={styles.tableCell}>{cls.counselor}</td>
                  <td style={styles.tableCell}>{cls.lecturer}</td>
                  <td style={styles.tableCell}>
                    <button style={styles.editButton} onClick={() => showEditModal(cls)}>
                      编辑
                    </button>
                    <button style={styles.deleteButton} onClick={() => deleteClass(cls.id)}>
                      删除
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {isModalVisible && (
        <div style={styles.modalOverlay} onClick={handleCancel}>
          <div style={styles.modalContent} onClick={(e) => e.stopPropagation()}>
            <h2 style={styles.modalHeader}>{isEditMode ? '编辑班级' : '添加班级'}</h2>
            <form onSubmit={handleSubmit}>
              <div style={styles.formGroup}>
                <label style={styles.formLabel} htmlFor="className">班级名称 *</label>
                <input
                  id="className"
                  type="text"
                  name="className"
                  value={formData.className}
                  onChange={handleInputChange}
                  style={styles.formInput}
                  placeholder="请输入班级名称"
                  required
                />
                {formErrors.className && <div style={styles.errorText}>{formErrors.className}</div>}
              </div>

              <div style={styles.formGroup}>
                <label style={styles.formLabel} htmlFor="major">专业</label>
                <select
                  id="major"
                  name="major"
                  value={formData.major}
                  onChange={(e) => setFormData(prev => ({ ...prev, major: parseInt(e.target.value) }))}
                  style={styles.formInput}
                >
                  <option value={1}>专业1</option>
                  <option value={2}>专业2</option>
                </select>
              </div>

              <div style={styles.formGroup}>
                <label style={styles.formLabel} htmlFor="counselor">导员</label>
                <input
                  id="counselor"
                  type="text"
                  name="counselor"
                  value={formData.counselor}
                  onChange={handleInputChange}
                  style={styles.formInput}
                  placeholder="请输入导员姓名"
                />
              </div>

              <div style={styles.formGroup}>
                <label style={styles.formLabel} htmlFor="lecturer">讲师</label>
                <input
                  id="lecturer"
                  type="text"
                  name="lecturer"
                  value={formData.lecturer}
                  onChange={handleInputChange}
                  style={styles.formInput}
                  placeholder="请输入讲师姓名"
                />
              </div>

              <div style={styles.formGroup}>
                <label style={styles.formLabel} htmlFor="description">描述</label>
                <textarea
                  id="description"
                  name="description"
                  value={formData.description}
                  onChange={handleInputChange}
                  style={styles.formTextarea}
                  placeholder="请输入班级描述信息"
                  rows={3}
                  maxLength={200}
                />
              </div>

              <div style={styles.formActions}>
                <button type="button" style={styles.cancelButton} onClick={handleCancel}>
                  取消
                </button>
                <button type="submit" style={styles.submitButton}>
                  确定
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default ClassManagement;